<?php include("../resources/views/header.php");?>
<?php 
    $form_type = !empty($user->token)?"auth":"registered";
    $unionid = !empty($wechat_user)?$wechat_user["original"]["unionid"]:'';
    $openid = !empty($wechat_user)?$wechat_user["original"]["openid"]:'';
    $need_update = (empty($user)&& !empty($wechat_user));
    $user_id = !empty($user->id)?$user->id:''; 
?>
<style type="text/css">
    .button_vcode{
        color: #fff;
        background: #ddd;
        padding: 3px 5px;
        border-radius: 3px;
        font-size: 12px;
        position: absolute;
        right: 5px;top: 11px;
        cursor: pointer;
    }
    .button_vcode.active{
        background: #1fb3ba;
    }
</style>
<main class="l-main" >
    <div class="l-main__inner">
        <form action="/oauth2/auth" method="POST" id="auth">
            <input type="hidden" name="client_id" value="<?=$client_id?>" />
            <input type="hidden" name="response_type" value="<?=$response_type?>" />
            <input type="hidden" name="scope" value="<?=$scope?>" />
            <input type="hidden" name="state" value="<?=$state?>" />
            <input type="hidden" name="token" id="token" value="<?=!empty($user->token)?$user->token:''?>"/>
            <div class="Message">
                <p class="l-content">应用“<?=$client->data[0]->name?>”请求链接您的拾光账号</p>
                <?php if(!empty($user->token)):?>
                <div class="l-content" style="padding-top:50px;text-align:center;">
                    <img class="head_pic"  src="<?='http://source.timepicker.cn'.$user->icon.'?imageView2/2/w/120'?>">
                    <div style="line-height:40px;">
                        <?php if ($user->sex != null) :?>
                        <span class="sex <?=$user->sex ? 'male':'female'?>"></span>
                        <?php endif ?>
                        <span><?=$user->name?></span>
                    </div>
                    <div class="form-group">
                        <input type="submit" name="submit" value="同意授权" class="btn btn--primary btn--block btn--lg" id="buttonLogin"/> 
                    </div>
                </div>
                <?php else:?>
                <div class="Message__media"> <img class="Message__icon" src="/img/logo.png"></img> </div>
                <div class="l-content">
                    <div class="form-group" style="position:relative" id="usernameBox">
                        <div class="form-control" style="padding-right:80px;" id="usernameContral">
                            <input type="text" name="username" class="form-input" placeholder="手机号" id="username" oninput="checkUserName(false)">
                        </div>
                        <span class="button_vcode" onclick="getVerifyCode(true,false)" id="buttonGetVcode">获取验证码</span>
                    </div>
                    <div class="form-group" id="vcodeBox">
                        <div class="form-control"> <input type="text" class="form-input" placeholder="验证码" id="vcode" oninput="checkVcode()"></div>
                    </div>
                    <div class="form-group" id="passwordBox">
                        <div class="form-control"> <input type="password" class="form-input" placeholder="密码(不得少于6位)" id="password" oninput="checkPwd()"></div>
                    </div>
                    <div class="form-group">
                        <input type="submit" name="submit" value="登录/注册" class="btn btn--primary btn--block btn--lg" id="buttonLogin"/> 
                    </div>
                    <div class="l-row mcolor">
                        <div class="l-col-4">
                            <div class="" style="text-align:left" id="resetPwd" onclick="resetPwd()">忘记密码？</div>
                        </div>
                        <div class="l-col-8" style="text-align:right">
                            <a href="http://timepicker.cn/md/agreement.html" style="text-align:right">《拾光协议》</a>
                        </div>
                    </div>
                </div>
                <?php endif ?>
            </div>
        </form>
    </div>
    
</main>

<?php include("../resources/views/footer.php");?>
<script type="text/javascript">
    var is_ok_uname = false;
    var is_ok_vcode = false;
    var is_ok_pwd = false;
    var is_ok = false;
    var token;
    var state = '<?=$state?>';
    localStorage.type = '<?=$form_type?>';
    //倒计时 60秒
    var countdown=60; 
    function settime(val) { 
        if (countdown == 0) { 
            val.addClass("active");    
            val.html("重新获取"); 
            countdown = 60; 
            return;
        }else { 
            val.removeClass("active");
            val.removeClass("active"); 
            val.html(countdown + "秒"); 
            countdown--; 
        } 
        setTimeout(function() { 
            settime(val) 
        },1000) 
    }
    //显示验证码组件
    function verifyFormationShow(){
        $("#vcode").val("");
        $("#buttonGetVcode").addClass("active");
        $("#vcodeBox,#buttonGetVcode").show();
        $("#usernameContral").css("padding-right","80px");
    }

    //验证账号
    function checkUserName(is_resetPwd){
        
        // 检测手机号是否正确的正则表达式：(1)必须全为数字;(2)必须是11位.(有人说还有10位的手机号,这里先不考虑);(3)必须以1开头(有人见过以2开头的手机号吗?)(4)第2位是34578中的一个.
        var patternPhone = /^1[34578]\d{9}$/;
        var username = $('#username').val();
        
        if( handleInput("username") && patternPhone.test(username) ){
            checKInput("username","success",true);
            is_ok_uname = true;
            // 这里调检测手机号是否已经注册的接口
            $.ajax({
                type: 'POST',
                url: 'http://<?=env("APP_URL")?>/restapi',
                data: $.param({ method:'GET',host:'user',path:'/user/exsit?phone='+username,query:{}}),
                dataType: 'json',
                success: function(data){
                    if (!data.error) {
                        //手机号未注册
                        verifyFormationShow();
                        $("#buttonLogin").val("注册并授权");
                        $("#passwordBox").show();
                        if(is_resetPwd) toast("手机号未注册");
                        localStorage.type = "registered";
                    }else{
                        
                        // 手机号已经注册
                        if (!is_resetPwd) {
                            $("#buttonLogin").val("登录并授权");
                            $("#vcodeBox,#buttonGetVcode").hide();
                            $("#usernameContral").css("padding-right",0);
                            toast("请直接登录");
                            localStorage.type = "login";
                        };
                    };
                },
                error: function(xhr, type){
                    toast('验证手机号Ajax error!');
                }
            })   
        }else{
            is_ok_uname = false;
            if (username.length>11) checKInput("username","danger",true);
        };
    }
    //获取验证码
    function getVerifyCode(need_unique,need_exsit){
        if ($("#buttonGetVcode").hasClass('active')) {
            if (is_ok_uname) {
                var query;
                if (need_unique) query = {phone:$("#username").val(),need_unique:1};
                if (need_exsit) query = {phone:$("#username").val(),need_exist:1};
                $.ajax({
                    type: 'POST',
                    url: 'http://<?=env("APP_URL")?>/restapi',
                    data: $.param({ method:'POST',host:'user',path:'/user/verifycode',query:query}),
                    dataType: 'json',
                    success: function(data){
                        if (!data.error) {
                            settime($('#buttonGetVcode'));
                            toast("发送成功，请注意查收")
                        }else{
                            toast("发送失败，稍后重试");
                        };
                    },
                    error: function(xhr, type){
                        toast('获取验证码Ajax error!');
                    }
                })
            }else{
                checKInput("username","danger",true);toast("账号错误");
            };
        };
    }
    //验证验证码
    function checkVcode(){
        var vcode = $("#vcode").val();
        if (handleInput("vcode") && vcode.length==4) {
            $.ajax({
                type: 'POST',
                url: 'http://<?=env("APP_URL")?>/restapi',
                data: $.param({ method:'POST',host:'user',path:'/user/verifycode/verify',query:{phone:$("#username").val(),verifycode:vcode}}),
                dataType: 'json',
                success: function(data){
                    if (!data.error) {
                        token = data.result.token;
                        is_ok_vcode = true;
                        checKInput("vcode","success",true);
                    }else{
                        toast(data.message);
                        is_ok_vcode = false;
                        checKInput("vcode","danger",true);
                    };
                },
                error: function(xhr, type){
                    console.log('Ajax error!');
                }
            })
        }else{
            is_ok_vcode = false;
            if (vcode.length>4) checKInput("vcode","danger",true);
        };
    }
    //验证密码
    function checkPwd(){
        var pwd = $("#password").val();
        handleInput("password");
        if (pwd.length>=6){
            checKInput("password","success",true);
            is_ok_pwd = true;
        }else{
            is_ok_pwd = false;
        }
    }

    //注册
    function registered(){
        var user_id = '';
        if(is_ok_uname && is_ok_pwd && is_ok_vcode) {
            var username = $("#username").val();
            var password = $("#password").val();
            $.ajax({
                type: 'POST',
                url: 'http://<?=env("APP_URL")?>/restapi',
                data: $.param({ method:'POST',host:'user',path:'/user',query:{phone:username,password:password,token:token}}),
                dataType: 'json',
                async : false,
                success: function(data){
                    notify('提交数据',false);
                    if (!data.error) {
                        toast("注册成功");
                        $("#token").val(data.result.token);
                        user_id = data.result.id;
                    }else{
                        window.notify('注册中',false);
                        toast("注册失败");
                    }
                },
                error: function(xhr, type){
                    window.notify('注册中',false);
                    alert('注册接口Ajax error!');
                }
            })
        }else{
            window.notify('注册中',false);
            if (!is_ok_uname) {checKInput("username","danger",true);toast("手机号错误");}
            if (!is_ok_pwd) {checKInput("password","danger",true);toast("密码至少为6位");}
            if (!is_ok_vcode) {checKInput("vcode","danger",true);toast("验证码错误");}
        };
        return user_id;
    }
    //登录
    function login(){
        var username = $("#username").val();
        var password = $("#password").val();
        var user_id = '';
        if (is_ok_uname && is_ok_pwd) {
            $.ajax({
                type: 'POST',
                url: 'http://<?=env("APP_URL")?>/restapi',
                data: $.param({ method:'POST',host:'user',path:'/user/login',query:{username:username,password:password,from_web:1}}),
                dataType: 'json',
                async : false,
                success: function(data){
                    if (!data.error) {
                        $("#token").val(data.result.token);
                        user_id = data.result.id;
                    }else{
                        window.notify('',false);
                        toast(data.message);
                    }
                },
                error: function(xhr, type){
                    window.notify('',false);
                    toast('登陆接口Ajax error!');
                }
            })
        }else{
            window.notify('',false);
            if (!is_ok_pwd) {checKInput("password","danger",true);toast("密码至少为6位");}
            if (!is_ok_uname) {checKInput("username","danger",true);toast("账号错误");}
        };
        return user_id;
    }
    //找回密码
    function resetPwd(){
        verifyFormationShow();
        localStorage.type = "findPwd";

        $("#buttonLogin").show();
        $("#resetPwd").hide();

        $("#buttonLogin").val("找回密码");

        $("#username").attr("oninput","checkUserName(true)");
        $("#buttonGetVcode").attr('onclick',"getVerifyCode(false,true)");
    }
    function findPwd(){
        var user_id='';
        if (is_ok_pwd && is_ok_uname && is_ok_vcode) {
            var username = $("#username").val();
            var password = $("#password").val();
            $.ajax({
                type: 'POST',
                url: 'http://<?=env("APP_URL")?>/restapi',
                data: $.param({ method:'POST',host:'user',path:'/user/findpassword',query:{phone:username,password:password,token:token}}),
                dataType: 'json',
                async : false,
                success: function(data){
                    notify("",false);
                    if (!data.error) {
                        $("#token").val(data.result.token);
                        toast("密码修改成功");
                        user_id = data.result.id;
                    }else{
                        toast("密码修改失败");
                        notify("",false);
                    }
                },
                error: function(xhr, type){
                    notify("",false);
                    console.log('Ajax error!');
                }
            })
        }else{
            notify("找回密码",false);
            if (!password) {checKInput("password","danger",true);toast("密码至少为6位");}
            if (!is_ok_vcode) {checKInput("vcode","danger",true);toast("验证码错误");}
            if (!is_ok_uname) {checKInput("username","danger",true);toast("账号错误");}
        };
        return user_id;
    }

    // 提交form表单
    $("#auth").submit(function(){
        notify('提交数据',true);
        var type = localStorage.type;
        var is_ok = false;
        var need_update = '<?=$need_update?>';
        var user_id='';
        if (type == "login") { user_id = login(); is_ok = (user_id==''||typeof(user_id)=='undefined')?false:true;}
        if (type == "registered") {user_id =  registered(); is_ok = (user_id==''|| typeof(user_id)=='undefined')?false:true;}
        if (type == "findPwd") {user_id =  findPwd();is_ok = (user_id==''||typeof(user_id)=='undefined')?false:true;}
        if (type == "auth") {is_ok = true;user_id = '<?=$user_id?>'}

        if (need_update && is_ok) {
            var unionid = '<?=$unionid?>';
            var openid  = '<?=$openid?>';
            $.ajax({
                type: 'POST',
                url: 'http://<?=env("APP_URL")?>/restapi',
                data: $.param({ method:'PUT',host:'user',path:'/user/'+user_id,query:{unionid:unionid,openid:openid}}),
                dataType: 'json',
                async : false,
                success: function(data){
                    if (!data.error) {

                    }else{
                        window.notify('',false);
                        toast(data.message);
                        is_ok = false;
                    }
                },
                error: function(xhr, type){
                    window.notify('',false);
                    toast('登陆接口Ajax error!');
                }
            })
        };
        return is_ok;
    })
</script>
